package com.sd.activity;

import java.util.Vector;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.alex.books.BaseBook;
import com.alex.books.BookMark;
import com.alex.books.BookPageFactory;
import com.alex.books.BookStore;
import com.alex.books.Chapter;
import com.alex.books.ReaderingInfo;
import com.alex.database.BookDao;
import com.alex.database.BookDatabaseHelper.Bookmark_TB;
import com.sd.app.AppInit;
import com.sd.util.AlexStringUtil;
import com.sd.util.LoadingProgressDialog;
import com.sd.view.BookMarkAdapter;
import com.sd.view.ChapterAdpater;
import com.sd.view.DialogManager;


/**
 * 
 * @author Alex.Lu
 * 
 */
public class BookInfoActivity extends BaseActivity implements OnItemClickListener, OnItemLongClickListener, OnClickListener {
    /** Called when the activity is first created. */
	
	public static final String BOOKDATA  = "bookdata"; 
	private TabHost tabhost;
	private TabHost subtabhost;
	private BaseBook book;
	private static int index;
	
	private ListView mChpaterLV;
	private ListView mBookMarkLV;
	private static int mBookId;
	
	private ImageButton mReturnBT;
	private TextView mBookName;
	
	private ImageView mBookConverIV;
	private TextView mBookNameTV;
	private TextView mWordNumberTV;
	private TextView mChapterNumberTV;
	private TextView mSourceTV;
	private TextView mAboutAuthor;
	private TextView mAboutBook;
	private ImageButton mPointChapterBT;
	
	public static Intent getBookInfo(Context context,int bookId){
		mBookId = bookId;
		Intent intent = new Intent(context, BookInfoActivity.class);
		index = 0;
		return intent;
	}
	
	public static Intent getBookContents(Context context,int bookId){
		mBookId = bookId;
		Intent intent = new Intent(context, BookInfoActivity.class);
		index = 1;
		return intent;
	}
	
	public static Intent getBookMark(Context context,int bookId){
		mBookId = bookId;
		Intent intent = new Intent(context, BookInfoActivity.class);
		index = 2;
		return intent;
	}
	
	
	private Handler mHandler =  new Handler() { 
		public void handleMessage(Message msg) {  
			switch (msg.what) {
			case 0:
				
				break;
			case 1:
				
				break;

			default:
				break;
			}
		    
			
			LoadingProgressDialog.dismiss();
			Vector<Chapter> chapters = BookStore.getInstance().getChapters(BookInfoActivity.this, mBookId);
		    ChapterAdpater chapterAdpater = new ChapterAdpater(BookInfoActivity.this, chapters);
		    mChpaterLV.setAdapter(chapterAdpater);
		    
		    Vector<BookMark> bookmarks = BookStore.getInstance().getBookMarks(BookInfoActivity.this, mBookId);
		    BookMarkAdapter bookmarkAdpater = new BookMarkAdapter(BookInfoActivity.this, bookmarks);
		    mBookMarkLV.setAdapter(bookmarkAdpater);
		      
		    book = BookStore.getInstance().getABook(BookInfoActivity.this, mBookId);
		    mBookName.setText(book.mBookName);
		    initBookInfo();
		    
			super.handleMessage(msg);   
		}
	};
	
	private class mThread implements Runnable{

		private int mWhat;
		private String mKeys;
		public mThread(int what){
			mWhat = what;
		}
		
		public mThread(int what,String keys){
			mWhat = what;
			mKeys = keys;
		}
		
		@Override
		public void run() {
			switch (mWhat) {
			case 0:
				mHandler.sendEmptyMessage(mWhat); 
				break;
			case 1:
				BookPageFactory.getInstance().geteratedCatalog2(BookInfoActivity.this,book, mKeys);
				Message msg = new Message();
				msg.what = mWhat;
				msg.obj = mKeys;
				mHandler.sendMessage(msg);
				
				break;

			default:
				break;
			}
			
		}
	}
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_bookinfo);
        
        mReturnBT = (ImageButton)findViewById(R.id.return_btn);
        mReturnBT.setOnClickListener(this);
        
        mPointChapterBT = (ImageButton)findViewById(R.id.points_chapter);
        mPointChapterBT.setOnClickListener(this);
        
        mBookName = (TextView)findViewById(R.id.bookname);
        book = (BaseBook)this.getIntent().getSerializableExtra(BOOKDATA);
        
        subtabhost = (TabHost)findViewById(R.id.sub_tabhost);
        subtabhost.setup();
        
        int[][] state = {{ android.R.attr.state_selected},{-android.R.attr.state_selected}}; 
        int[] color = {this.getResources().getColor(R.color.blue),this.getResources().getColor(R.color.black)};
        ColorStateList colorStateList = new ColorStateList(state,color); 
        
        TextView bookInfo = new TextView(this);
        bookInfo.setText("书籍信息");
        bookInfo.setGravity(Gravity.CENTER);
        bookInfo.setTextSize(16);
        bookInfo.setTextColor(colorStateList);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        params.weight = 1;
        bookInfo.setLayoutParams(params);
        bookInfo.setBackgroundResource(R.drawable.search_top_btn_);
        
        TextView bookcontent = new TextView(this);
        bookcontent.setText("目录");
        bookcontent.setBackgroundResource(R.drawable.search_top_btn_);
        bookcontent.setTextColor(colorStateList);
        bookcontent.setTextSize(16);
        bookcontent.setGravity(Gravity.CENTER);
        bookcontent.setLayoutParams(params);
        
        TextView bookboomark = new TextView(this);
        bookboomark.setText("书签");
        bookboomark.setGravity(Gravity.CENTER);
        
        bookboomark.setTextColor(colorStateList);
        bookboomark.setTextSize(16);
        bookboomark.setLayoutParams(params);
        bookboomark.setBackgroundResource(R.drawable.search_top_btn_);
        
        TextView bookintroduce = new TextView(this);
        bookintroduce.setText("作品介绍");
        bookintroduce.setBackgroundResource(R.drawable.bookinfo_bg_);
        bookintroduce.setTextColor(colorStateList);
        bookintroduce.setTextSize(16);
        bookintroduce.setGravity(Gravity.CENTER);
        
        TextView authorintroduce = new TextView(this);
        authorintroduce.setText("作者介绍");
        authorintroduce.setBackgroundResource(R.drawable.bookinfo_bg_);
        authorintroduce.setTextColor(colorStateList);
        authorintroduce.setTextSize(16);
        authorintroduce.setGravity(Gravity.CENTER);
        
        subtabhost.addTab(subtabhost.newTabSpec("sub_tab1")     
                .setIndicator(bookintroduce)
                .setContent(R.id.sub_tab1));     
        subtabhost.addTab(subtabhost.newTabSpec("sub_tab2")     
                .setIndicator(authorintroduce)
                .setContent(R.id.sub_tab2));   
        
        tabhost = (TabHost)findViewById(R.id.tabhost);
        tabhost.setup();
        
        tabhost.addTab(tabhost.newTabSpec("tab1")     
                .setIndicator(bookInfo)
                .setContent(R.id.tab1));     
        tabhost.addTab(tabhost.newTabSpec("tab2")     
                .setIndicator(bookcontent)
                .setContent(R.id.tab2));   
        tabhost.addTab(tabhost.newTabSpec("tab3")
                .setIndicator(bookboomark)
                .setContent(R.id.tab3));   
        tabhost.setCurrentTab(index);
        
        mChpaterLV = (ListView)findViewById(R.id.chapters_list);
        mChpaterLV.setOnItemClickListener(this);
        
        mBookMarkLV = (ListView)findViewById(R.id.bookmark_list);
        mBookMarkLV.setOnItemClickListener(this);
        
        LoadingProgressDialog.show(this, R.string.msg_loading);
        new Thread(new mThread(0)).start();
        
    }
    
	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
		// TODO Auto-generated method stub
		if(parent.getId() == mChpaterLV.getId()){
			Chapter chapter = (Chapter)parent.getItemAtPosition(position);
			ReaderingInfo readeringInfo = new ReaderingInfo();
			readeringInfo.mCurChapter = chapter;
			readeringInfo.mIndex = chapter.mChapterIndex;
			readeringInfo.mMarkPos = chapter.mPosBegin;
			Intent intent = new Intent();
			intent.setClass(this, ReadBookActivity.class);
			intent.putExtra(ReadBookActivity.READINGINFO, readeringInfo);
			intent.putExtra(ReadBookActivity.BOOK_ID, mBookId);
			//setResult(RESULT_OK,intent);
			//finish();
			startActivity(intent);
			finish();
		}else if(parent.getId() == mBookMarkLV.getId()){
			BookMark bookMark = (BookMark)parent.getItemAtPosition(position);
			ReaderingInfo readeringInfo = new ReaderingInfo();
			readeringInfo.mCurChapter = bookMark.mChapter;
			readeringInfo.mIndex = bookMark.mChapter.mChapterIndex;
			readeringInfo.mMarkPos = bookMark.mMarkPos;
			Intent intent = new Intent();
			intent.setClass(this, ReadBookActivity.class);
			intent.putExtra(ReadBookActivity.READINGINFO, readeringInfo);
			intent.putExtra(ReadBookActivity.BOOK_ID, mBookId);
			//setResult(RESULT_OK,intent);
			//finish();
			startActivity(intent);
			finish();
		}
	}
	

	private void initBookInfo(){
		mBookConverIV = (ImageView)findViewById(R.id.book_conver);
		mBookNameTV = (TextView)findViewById(R.id.book_name);
		mWordNumberTV = (TextView)findViewById(R.id.word_number);
		mAboutAuthor = (TextView)findViewById(R.id.about_author);
		mAboutBook = (TextView)findViewById(R.id.about_book);
		mChapterNumberTV = (TextView)findViewById(R.id.chapter_number);
		mSourceTV = (TextView)findViewById(R.id.source);
		
		if(AlexStringUtil.isUnknownString(book.mBookCover)){
			mBookConverIV.setBackgroundResource(R.drawable.testbook_bg);
		}else{
			mBookConverIV.setBackgroundDrawable(new BitmapDrawable(AppInit.getInstance().APP_BOOKS + book.mBookCover));
		}
		
		if(AlexStringUtil.isUnknownString(book.mBookAuthor)){
			book.mBookAuthor = "未知";
		}
		mBookNameTV.setText("作者："+book.mBookAuthor);
		mWordNumberTV.setText("字数："+book.mWordNumber);
		if(AlexStringUtil.isUnknownString(book.mAboutAuthor)){
			book.mAboutAuthor = "暂无作家信息";
		}
		mAboutAuthor.setText(book.mAboutAuthor);
		mAboutBook.setText(book.mAboutBook);
		mChapterNumberTV.setText("章节："+book.mChapterNumber);
		if(AlexStringUtil.isUnknownString(book.mSource)){
			book.mSource = "未知";
		}
		
		mSourceTV.setText("版权来源：" + book.mSource);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		// TODO Auto-generated method stub
		if(parent.getId() == mBookMarkLV.getId()){
			BookMark bookMark = new BookMark();
			Cursor c = (Cursor)parent.getItemAtPosition(position);
			bookMark.id = c.getInt(c.getColumnIndex(Bookmark_TB._ID));
			c.close();
			BookDao.getInstance().deleteBookMarks(this, bookMark.id);
			Cursor c0 = BookDao.getInstance().queryBookMarks(this,book.mBookId);
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		/*chapterAdpter.getCursor().close();
		bookMarkAdpter.getCursor().close();*/
		
		super.onDestroy();
	}

	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.return_btn:
			finish();
			break;
		case R.id.points_chapter:
			DialogManager.getInstance().createPointChapter(this, this);
			break;
		case R.id.pick_up_ji:
		case R.id.pick_up_hui:
		case R.id.pick_up_jie:
		case R.id.pick_up_juan:
		case R.id.pick_up_zhang:
			String keys = (String)v.getTag();
			DialogManager.getInstance().dismiss();
			 LoadingProgressDialog.show(this, R.string.msg_loading);
			 new Thread(new mThread(1,keys)).start();
			break;
		default:
			break;
		}
	}
    
	
}